#!/usr/bin/env python3
"""
通用子模块镜像管理器
自动发现、评估和配置最优镜像
"""

import subprocess
import sys
import json
import time
from pathlib import Path
from urllib.parse import urlparse
import argparse

class UniversalMirrorManager:
    def __init__(self, git_cmd="git"):
        self.git_cmd = git_cmd
        self.mirror_sources = [
            "https://gitee.com/mirrors",      # 官方镜像
            "https://gitee.com/uesoft",       # UESOFT 镜像
            "https://gitcode.com/mirrors",    # 腾讯云镜像
        ]
        
    def run_git(self, args, check=False, timeout=30):
        """运行 git 命令"""
        try:
            cmd = [self.git_cmd] + args
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
            return result.returncode == 0, result.stdout.strip()
        except Exception as e:
            return False, str(e)
    
    def extract_project_name(self, git_url):
        """从 Git URL 提取项目名称"""
        parsed = urlparse(git_url)
        path = parsed.path.strip('/')
        
        # 处理 .git 后缀
        if path.endswith('.git'):
            path = path[:-4]
        
        # 提取项目名（最后一部分）
        project_name = path.split('/')[-1]
        return project_name
    
    def generate_mirror_urls(self, original_url, project_name):
        """为原始 URL 生成所有可能的镜像 URL"""
        mirror_urls = []
        
        for source in self.mirror_sources:
            # 生成镜像 URL
            mirror_url = f"{source}/{project_name}"
            mirror_urls.append(mirror_url)
            
            # 如果项目名有变体，也尝试
            if 'lib' in project_name and not project_name.startswith('lib'):
                alt_name = project_name.replace('lib', '')
                mirror_urls.append(f"{source}/{alt_name}")
        
        return mirror_urls
    
    def evaluate_mirror(self, mirror_url):
        """评估镜像质量"""
        print(f"  评估: {mirror_url}")
        
        # 检查可用性
        success, _ = self.run_git(["ls-remote", mirror_url], timeout=10)
        if not success:
            return 0, "不可用"
        
        # 检查标签数量（简单完整性检查）
        success, output = self.run_git(["ls-remote", "--tags", mirror_url], timeout=10)
        if success:
            tag_count = len([line for line in output.split('\n') if line])
            if tag_count > 10:
                return 90, f"优秀 ({tag_count} 标签)"
            elif tag_count > 5:
                return 70, f"良好 ({tag_count} 标签)"
            else:
                return 50, f"一般 ({tag_count} 标签)"
        
        return 60, "可用"
    
    def find_best_mirror(self, original_url):
        """为原始 URL 寻找最优镜像"""
        project_name = self.extract_project_name(original_url)
        print(f"为 {project_name} 寻找最优镜像...")
        
        mirror_urls = self.generate_mirror_urls(original_url, project_name)
        best_mirror = None
        best_score = 0
        best_reason = ""
        
        for mirror_url in mirror_urls:
            score, reason = self.evaluate_mirror(mirror_url)
            print(f"    {mirror_url} -> 得分: {score}, 原因: {reason}")
            
            if score > best_score:
                best_score = score
                best_mirror = mirror_url
                best_reason = reason
        
        return best_mirror, best_score, best_reason
    
    def setup_mirror_for_submodule(self, submodule_path, original_url):
        """为单个子模块设置镜像"""
        print(f"\n处理子模块: {submodule_path}")
        print(f"原始 URL: {original_url}")
        
        # 寻找最优镜像
        best_mirror, score, reason = self.find_best_mirror(original_url)
        
        if best_mirror and score >= 50:  # 及格分数
            print(f"✅ 找到镜像: {best_mirror} (得分: {score})")
            
            # 配置镜像规则
            config_name = f"url.{best_mirror}.insteadOf"
            success, _ = self.run_git(["config", "--local", config_name, original_url])
            
            if success:
                print(f"✅ 镜像配置成功: {original_url} -> {best_mirror}")
                return True
            else:
                print("❌ 镜像配置失败")
                return False
        else:
            print(f"❌ 未找到合适的镜像 (最佳得分: {score})")
            return False
    
    def process_all_submodules(self):
        """处理所有子模块"""
        print("=== 开始处理所有子模块 ===")
        
        # 获取所有子模块
        success, output = self.run_git(["submodule", "status"])
        if not success:
            print("❌ 无法获取子模块信息")
            return False
        
        submodules = []
        for line in output.split('\n'):
            if line.strip():
                parts = line.split()
                if len(parts) >= 2:
                    submodules.append({
                        'path': parts[1],
                        'commit': parts[0].lstrip('+-')
                    })
        
        if not submodules:
            print("ℹ️  没有找到子模块")
            return True
        
        print(f"找到 {len(submodules)} 个子模块")
        
        # 获取每个子模块的原始 URL
        for submodule in submodules:
            success, url = self.run_git([
                "config", "--file", ".gitmodules", 
                f"submodule.{submodule['path']}.url"
            ])
            
            if success:
                submodule['original_url'] = url
            else:
                print(f"❌ 无法获取子模块 {submodule['path']} 的 URL")
                continue
        
        # 为每个子模块设置镜像
        success_count = 0
        for submodule in submodules:
            if 'original_url' in submodule:
                if self.setup_mirror_for_submodule(submodule['path'], submodule['original_url']):
                    success_count += 1
        
        print(f"\n=== 处理完成 ===")
        print(f"成功配置: {success_count}/{len(submodules)} 个子模块")
        
        return success_count > 0
    
    def init_submodules(self):
        """初始化子模块"""
        print("=== 初始化子模块 ===")
        success, output = self.run_git(["submodule", "update", "--init", "--recursive"])
        
        if success:
            print("✅ 子模块初始化完成")
        else:
            print("❌ 子模块初始化失败")
        
        return success

def main():
    parser = argparse.ArgumentParser(description='通用子模块镜像管理器')
    parser.add_argument('--git-cmd', default='git', help='Git 命令路径')
    parser.add_argument('--setup', action='store_true', help='设置所有子模块镜像')
    parser.add_argument('--init', action='store_true', help='初始化子模块')
    parser.add_argument('--check', action='store_true', help='检查当前配置')
    
    args = parser.parse_args()
    
    manager = UniversalMirrorManager(args.git_cmd)
    
    if args.setup:
        manager.process_all_submodules()
    elif args.init:
        manager.init_submodules()
    elif args.check:
        success, output = manager.run_git(["config", "--local", "--list"])
        if success:
            print("当前镜像配置:")
            for line in output.split('\n'):
                if 'insteadOf' in line:
                    print(f"  {line}")
        else:
            print("无法获取配置")
    else:
        parser.print_help()

if __name__ == '__main__':
    main()
